// 加载模块
const express = require('express')
const utility = require('utility')
const multer = require('multer')
// 加载自定义模块
const bd = require('./连接服务器')
// 创建 router 实例
const router = express.Router()
// 保存图片路径
let upload = multer({ dest: 'uploads/' })
// 接口
// 获取用户信息
router.get('/userinfo', (req, res) => {
    bd(`select * from user where id=` + req.user.id, (err, result) => {
        if (err) throw err
        res.send({ status: 0, mesage: '获取用户数据成功', data: result })
    })
})
// 更改用户信息
router.post('/userinfo', (req, res) => {
    let { id, nickname, email } = req.body
    // 验证用户发来的信息
    if (req.user.id != req.body.id) {
        // 代表用户验证不通过
        res.send({ status: 1, message: '验证不通过' })
    } else {
        // 验证通过
        bd(`update user set nickname='${nickname}',email='${email}' where id='${id}'`, (err, result) => {
            if (err) throw err
            res.send({ status: 0, message: '数据修改成功' })
        })
    }
})
// 修改密码
router.post('/updatepwd', (req, res) => {
    // 获取id
    let id = req.user.id
    // 获取新旧密码
    let { oldPwd, newPwd } = req.body
    // 转化密码
    oldPwd = utility.md5(oldPwd)
    newPwd = utility.md5(newPwd)
    //验证
    bd(`select * from user where id='${id}' and password='${oldPwd}'`, (err, result) => {
        if (err) throw err
        if (result.length > 0) {
            bd(`update user set password='${newPwd}' where id='${id}'`, (err, result) => {
                if (err) throw err
                res.send({ status: 0, message: '密码更改成功' })
            })
        } else {
            res.send({ status: 1, message: '原密码错误' })
        }
    })
})
// 修改头像
router.post('/update/avatar', upload.single('avatar'), (req, res) => {
    let id = req.user.id
    bd(`update user set user_pic='${req.body.avatar}' where id='${id}'`, (err, result) => {
        if (err) throw err
        res.send({ status: 0, message: '头像上传成功' })
    })

})
// 输出 router
module.exports = router